package ext.tianma.upload;

import java.beans.PropertyVetoException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import org.json.JSONObject;

import ext.drawing.BorrowWorkflowUtil;
import wt.content.ApplicationData;
import wt.content.ContentHelper;
import wt.content.ContentHolder;
import wt.content.ContentRoleType;
import wt.content.ContentServerHelper;
import wt.doc.WTDocument;
import wt.doc.WTDocumentMaster;
import wt.doc.WTDocumentMasterIdentity;
import wt.fc.Identified;
import wt.fc.IdentityHelper;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.fc.WTObject;
import wt.fc.collections.WTValuedHashMap;
import wt.folder.Folder;
import wt.folder.FolderHelper;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.inf.library.WTLibrary;
import wt.part.WTPart;
import wt.part.WTPartDescribeLink;
import wt.part.WTPartReferenceLink;
import wt.pdmlink.PDMLinkProduct;
import wt.pom.Transaction;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.Mastered;
import wt.workflow.engine.ProcessData;
import wt.workflow.engine.WfProcess;
import wt.workflow.engine.WfVariable;

public class creatDocuments {

	/**
	 * 创建文档对象或更新文档主内容
	 * @param wid
	 * @param docKey
	 * @param docName
	 * @param values
	 * @param primaryContent
	 * @return
	 * @throws Exception
	 */
	public static WTDocument createDoc(String wid, String docKey, String docName, String values, Object primaryContent)
			throws Exception {
		
		
		WfProcess process = MyUtil.GetWfProcess(wid);
		ProcessData processData = process.getContext();
		WTDocument doc = (WTDocument) processData.getValue(docKey);

		if (doc == null) {
			String conName = "";
			WTObject wtObject = BorrowWorkflowUtil.getPBO(process);

			WTPart part = null;
			if (wtObject != null && wtObject instanceof WTPart) {
				part = (WTPart) wtObject;
			}

			if (part != null) {
				WTContainer con = part.getContainer();
				conName = con.getName();
			}
			
			doc = createNewDoc(process, docKey, conName, docName, primaryContent);
			createRefLink(part, doc);
			
		} else {
			File file = (File) primaryContent;
			String fileName = file.getName();
			InputStream io = new FileInputStream(file);
			replacePrimaryContent(doc, io, fileName);

			//设置上传文件名为文档对象名称
			int lastFileSeperatorIndex = fileName.lastIndexOf(".");
			String showName = fileName.substring(0, lastFileSeperatorIndex);
			Identified identified = (Identified) doc.getMaster();
			WTDocumentMasterIdentity masteridentity = (WTDocumentMasterIdentity) identified.getIdentificationObject();
			masteridentity.setName(showName);
			identified = IdentityHelper.service.changeIdentity(identified, masteridentity);
			PersistenceServerHelper.manager.update(doc.getMaster());
			PersistenceHelper.manager.refresh(doc);
		}
		
		
		//获取页面选中的值并赋值到流程中
		JSONObject valuesObj = new JSONObject(values);
		@SuppressWarnings("unchecked")
		Iterator<String> it = valuesObj.keys();
		while (it.hasNext()) {
			// 获得key
			String key = it.next();
			String value = valuesObj.getString(key).trim();
			
			//为流程变量赋值
			WfProcess proc = MyUtil.GetWfProcess(wid);
			WfVariable VariableMainType = proc.getContext().getVariable(key);
			VariableMainType.setValue(value);
			wt.fc.PersistenceHelper.manager.save (proc);
		}
		 
		
		return doc;
	}

	/**
	 * 新建文档对象
	 * @param process
	 * @param docKey
	 * @param conName
	 * @param docName
	 * @param primaryContent
	 * @return
	 * @throws WTException
	 */
	public static WTDocument createNewDoc(WfProcess process, String docKey, String conName, String docName, Object primaryContent) throws WTException {
		boolean flagAccess = SessionServerHelper.manager.setAccessEnforced(false);
		WTDocument doc = WTDocument.newWTDocument();
		Transaction trx = new Transaction();
		try {
			trx.start();

			String Folder = "/Default";
			Folder location = null;
			WTContainer container = null;
			
			doc.setName(docName);

			if (conName != null) {
				QueryResult qr = MyUtil.getQueryResult(WTContainer.class, WTContainer.NAME, conName);
				while (qr.hasMoreElements()) {
					container = (WTContainer) qr.nextElement();
				}
				// 获取容器的引用
				WTContainerRef containerRef = WTContainerRef.newWTContainerRef(container);
				
				Object obj = containerRef.getObject();
				if(obj instanceof PDMLinkProduct) {
					PDMLinkProduct product = (PDMLinkProduct) containerRef.getObject();
					doc.setContainer(product);
				}else if(obj instanceof WTLibrary) {
					WTLibrary library = (WTLibrary) containerRef.getObject();
					doc.setContainer(library);
				}
				
				location = FolderHelper.service.getFolder(Folder, containerRef);
			}

			if (location != null) {
				WTValuedHashMap map = new WTValuedHashMap();
				map.put(doc, location);
				FolderHelper.assignLocations(map);
			}

			doc = (WTDocument) PersistenceHelper.manager.save(doc);
			doc = (WTDocument) PersistenceHelper.manager.refresh(doc);
			ApplicationData appData = ApplicationData.newApplicationData(doc);
			appData.setRole(ContentRoleType.PRIMARY);
			appData = (ApplicationData) PersistenceHelper.manager.save(appData);
			if (primaryContent != null) {

				if (primaryContent instanceof File) {
					File file = (File) primaryContent;
					if (file.exists()) {
						appData.setFileName(file.getName());
						appData.setUploadedFromPath(file.getAbsolutePath());
						appData = ContentServerHelper.service.updateContent(doc, appData, file.getAbsolutePath());
					}
				} else if (primaryContent instanceof InputStream) {
					InputStream ins = (InputStream) primaryContent;
					appData = ContentServerHelper.service.updateContent(doc, appData, ins);
				}
			}
			doc = (WTDocument) PersistenceServerHelper.manager.restore(doc);

			WfVariable VariableMainType = process.getContext().getVariable(docKey);
			VariableMainType.setValue(doc);
			
			process = (WfProcess)wt.fc.PersistenceHelper.manager.save (process);
			wt.fc.PersistenceHelper.manager.refresh(process);
		    String docKeyValue = VariableMainType.getValue().toString();

			trx.commit();
			trx = null;
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WTPropertyVetoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (PropertyVetoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (trx != null) {
				trx.rollback();
			}
			SessionServerHelper.manager.setAccessEnforced(flagAccess);
		}
		
		return doc;
	}

	/**
	 * 更新文档主内容
	 * 
	 * @param holder
	 * @param in
	 * @param name
	 */
	public static void replacePrimaryContent(ContentHolder holder, InputStream in, String name) {
		try {
			QueryResult qr = ContentHelper.service.getContentsByRole(holder, ContentRoleType.PRIMARY);

			while (qr.hasMoreElements()) {
				ApplicationData oAppData = (ApplicationData) qr.nextElement();
				ContentServerHelper.service.deleteContent(holder, oAppData);
			}

			updateContent(holder, in, name, ContentRoleType.PRIMARY);
		} catch (WTPropertyVetoException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 更新主内容或附件
	 * 
	 * @param holder
	 * @param in
	 * @param name
	 * @param type
	 */
	public static void updateContent(ContentHolder holder, InputStream in, String name, ContentRoleType type) {

		boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
		Transaction trx = new Transaction();

		try {
			trx.start();
			PersistenceServerHelper.manager.lock(holder);
			ApplicationData data = ApplicationData.newApplicationData(holder);
			data.setRole(type);
			data.setFileName(name);
			data = ContentServerHelper.service.updateContent(holder, data, in);
			trx.commit();
			trx = null;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (trx != null) {
				trx.rollback();
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			SessionServerHelper.manager.setAccessEnforced(enforce);
		}
	}
	
	/**
	 * 文档与物料建立参考关系
	 * 
	 * @param part
	 * @param doc
	 * @return
	 * @throws Exception
	 */
	public static WTPartReferenceLink createRefLink(WTPart part, WTDocument doc)
			throws Exception {
		WTDocumentMaster master = (WTDocumentMaster)doc.getMaster();
		WTPartReferenceLink link = WTPartReferenceLink.newWTPartReferenceLink(part, master);
		PersistenceServerHelper.manager.insert(link);
		return link;
	}

}
